package com.xxxx.server.controller;

import com.xxxx.server.config.security.component.JwtTokenUtils;
import com.xxxx.server.pojo.Admin;
import com.xxxx.server.pojo.AdminLoginParam;
import com.xxxx.server.pojo.RespBean;
import com.xxxx.server.pojo.Visualdata;
import com.xxxx.server.service.IAddUserService;
import com.xxxx.server.service.IAdminService;
import com.xxxx.server.service.IVisualdataService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.time.LocalDate;
import java.util.List;

/**
 * 登录
 */
@Api(tags = "用户登录")
@RestController
@RequestMapping("/")
public class LoginController {

    @Autowired
    private IAdminService adminService;

    @Autowired
    private IAddUserService addUserService;

    @Autowired
    private IVisualdataService visualdataService;

    @ApiOperation(value = "登录之后返回token")
    @PostMapping("/login")
    public RespBean login(@RequestBody AdminLoginParam adminLoginParam,HttpServletRequest request){
/**每次登陆时自动同步数据,如果今天已经同步过数据则更新数据
 *
 */




            return adminService.login(adminLoginParam.getUsername(),adminLoginParam.getPassword()
                    ,adminLoginParam.getCaptcha()
                    ,request);
    }

    @ApiOperation(value = "获取当前登录用户的信息")
    @GetMapping("/system/admin")
    public Admin getUserInfo(Principal principal){
        if (principal == null){
            return null;
        }
        String username = principal.getName();
        Admin admin = adminService.getAdminByUserName(username);
        admin.setPassword(null);
       admin.setAuthorityList(adminService.getAuthorityByAdminId(admin.getId()));
        return admin;
    }

    @ApiOperation(value = "退出登录")
    @PostMapping("/logout")
    public RespBean logout(){
        //将token失效时间设置为now
        JwtTokenUtils.setExpirationDateNow();

        Visualdata visualdata=new Visualdata();
        LocalDate today= LocalDate.now();
        Integer visualdataId=visualdataService.getVisualdataIdByTodayId(today);
        visualdata.setId(visualdataId);
        visualdata.setTotalUsers(visualdataService.getTodayUsers());
        visualdata.setTotalLectures(visualdataService.getTodayLectures());
        visualdata.setTotalReverse(visualdataService.getTodayReverses());
        visualdata.setRecordDate(today);
        visualdataService.updateById(visualdata);
        System.out.println("更新了数据可视化!");
        return RespBean.success("注销成功！");
    }

}
